package com.afish.syl.lib.api.core.autoupdate.appupdate;

import java.io.File;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.util.Log;
import android.widget.Toast;

import com.afish.syl.lib.api.core.afishpublic.store.StoreUtils;
import com.afish.syl.lib.api.core.toast.AFishToast;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;



/**
 * 新版本更新信息
 *
 * @author 袁东亮
 * @since 2013_12_12
 *
 */
public class NewVersion {
	private String tag = "Config";
	private int newVersionCode;
	private String newVersionName;
	private Context context;
	private String downloadPath;
	private String appVersion;
	private String newApkName;
	private String appInfo;
	private ProgressDialog progress;
	private File file;
	private int apkSize;

	/**
	 * 构造函数
	 *
	 */
	public NewVersion(Context context, String downloadPath, String appVersion) {
		this.context = context;
		this.downloadPath = downloadPath;
		this.appVersion = appVersion;
	}

	/**
	 * 检测更新
	 *
	 * @throws Exception
	 */
	public void checkUpdateVersion() throws Exception {
		if (isNetworkAvailable()) {
		} else {
			Toast.makeText(context, "网络不可用！请检查网络或稍后再试", Toast.LENGTH_LONG).show();
		}
		String sUrl = downloadPath + appVersion;
		FinalHttp jwHttp = new FinalHttp();
		jwHttp.get(sUrl, new AjaxCallBack<String>() {
			@Override
			public void onSuccess(String s) {
				if (getServerVersion(s)) {
					if (newVersionCode > CurrentVersion
							.getVersionCode(context)) {
						try {
							showUpdateDialog();
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
			}
		});
	}

	/**
	 * 获取新版本信息
	 *
	 * @param newVersionJson
	 * @return
	 */
	private boolean getServerVersion(String newVersionJson) {

		try {
			JSONArray jsonArray = new JSONArray(newVersionJson);
			if (jsonArray.length() > 0) {
				JSONObject jsonObject = jsonArray.getJSONObject(0);
				newVersionCode = Integer.parseInt(jsonObject
						.getString("versionCode"));
				newVersionName = jsonObject.getString("versionName");
				newApkName = jsonObject.getString("apkname");
				apkSize = Integer.parseInt(jsonObject.getString("apksize"));
				appInfo = jsonObject.getString("apkinfo");
			}
		} catch (JSONException e) {
			newVersionCode = -1;
			newVersionName = "";
			newApkName = "";
			Log.e(tag, e.getMessage());
			return false;
		}
		return true;
	}

	/**
	 * 显示更新对话框
	 */
	private void showUpdateDialog() {
		StringBuilder sb = new StringBuilder();
		sb.append("当前版本：");
		sb.append(CurrentVersion.getVersinName(context));
		sb.append("\n");
		sb.append("发现新版本：");
		sb.append(newVersionName);
		sb.append("\n");
		sb.append("大小：");
		System.out.println(apkSize);
		sb.append(byteToMB(apkSize) + "M");
		sb.append("\n");
		sb.append("更新信息:");
		sb.append("\n");
		sb.append(appInfo);
		sb.append("\n");
		Builder builder = new Builder(context);
		builder.setTitle("软件更新");
		builder.setMessage(sb);
		builder.setPositiveButton("现在更新", new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				progress = new ProgressDialog(context);
				progress.setTitle("正在下载...");
				progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
				progress.setIndeterminate(false);
				progress.setProgress(0);
				progress.show();
				downloadApk(downloadPath + newApkName);
			}
		});
		builder.setNegativeButton("暂不更新", null);
		builder.create().show();
	}

	/**
	 * 下载文件
	 */
	private void downloadApk(String sDownUrl) {
		String sApkPath = StoreUtils.getSDPath()  + newApkName;
		FinalHttp jwHttp = new FinalHttp();
		jwHttp.download(sDownUrl, sApkPath, new AjaxCallBack<File>() {

			@Override
			public int getRate() {
				return super.getRate();
			}

			@Override
			public AjaxCallBack<File> progress(boolean progress, int rate) {
				return super.progress(progress, rate);
			}

			@Override
			public void onStart() {
				super.onStart();
			}

			@Override
			public void onLoading(long count, long current) {
				super.onLoading(count, current);
				progress.setProgressNumberFormat("%1d k/%2d k");
				progress.setMax(byteToKB((int) count));
				progress.setProgress(byteToKB((int) current));
			}

			@Override
			public void onSuccess(File f) {
				file = f;
				try {
					Thread.sleep(3000);
					showcomplelteDiloage();
				} catch (InterruptedException e) {
					progress.dismiss();
					e.printStackTrace();
				}
			}

			@Override
			public void onFailure(Throwable t, int errorNo, String strMsg) {
				AFishToast.ToastShow("自动更新出现异常,请您到官网下载");
			}
		});


	}

	/**
	 * 下载完成对话框
	 */
	private void showcomplelteDiloage() {
		Builder builder = new Builder(context);
		builder.setTitle("下载通知");
		builder.setMessage("下载完成是否安装？");
		builder.setPositiveButton("确定", new OnClickListener() {

			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				installNewApk();
				progress.dismiss();
			}
		});
		builder.setNegativeButton("取消", new OnClickListener() {

			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				progress.dismiss();
			}
		});
		builder.create().show();
	}

	/**
	 * 安装文件
	 */
	private void installNewApk() {
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setDataAndType(Uri.fromFile(file),
				"application/vnd.android.package-archive");
		context.startActivity(intent);
	}

	/**
	 * 字节转换为Mb
	 *
	 * @param bt
	 * @return Mb大小
	 */
	private float byteToMB(int bt) {
		int mb = 1024 * 1024;
		float f = (float) bt / mb;
		float temp = Math.round(f * 100);
		return temp / 100;

	}

	/**
	 * 字节转换为kb
	 *
	 * @param bt
	 * @return kb大小
	 */
	private int byteToKB(int bt) {
		return Math.round(bt / 1024);
	}

	/**
	 * 检测网络是否可用
	 *
	 * @return 是否可用
	 */
	private boolean isNetworkAvailable() {
		ConnectivityManager cm = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo ni = cm.getActiveNetworkInfo();
		return (ni != null && ni.isAvailable());
	}
}
